/*
 * 项目管理的界面控制器
 */
public class ProjectManageController
{
    /*public String pid;///项目id
    //public String type;///显示类型
    public Boolean isEdit{get;set;}//是否为编辑状态
    public Boolean isProject {get;set;}//是否为项目
    public String projectJson {get;set;}//项目结构的json
    public String projectListJson {get;set;}//项目列表json
    public ProjectManageDetail__c pmd {get;set;}//选中的子任务
    public DevelopProject__c dp {get;set;}//选中的项目
    public List<ProjectManageDetail__c> pmdList;
    public List<DevelopProject__c> dpList ;
    public Id uid ;
    //==================传递的参数=====================
    public String pdId{get;set;}//选中的子任务的Id 
    public String fatherId {get;set;}///新增子任务(子节点)时候的 父节点
    public String dpId {get;set;}//选中的项目的Id
    public Boolean isSuccess {get;set;}//操作是否成功

    public ProjectManageController(ApexPages.StandardController stdController)
    {
        pmd =new ProjectManageDetail__c();
        dp = new DevelopProject__c();

        pmdList = new List<ProjectManageDetail__c>();
        dpList = new List<DevelopProject__c>();
        //type = System.currentPageReference().getParameters().get('type');
        pid =  System.currentPageReference().getParameters().get('id');
        if(pid == null){
            getProjects();
        }else{
            getProjectStruct();
        }
        uid = UserInfo.getUserId();

    }
    //=================================项目列表==================================== 
    ///获取所有项目 生成列表
    public void getProjects(){
        projectListJson = '[';
        dpList = [select Id,name,Status__c,EstimateDate__c,OwnerId from DevelopProject__c where Status__c !='完成' order by Status__c ];
        integer i = 0;
        for(DevelopProject__c dp:dpList){
            i++;
            String node ='';
            node +='{';
            node += 'name:"'+dp.Name+ ' ['+dp.Status__c+']",';
            node += 'Id:"'+dp.Id +'"';
            node += '}';

            projectListJson += node; 
            if(i != dpList.size())projectListJson +=',';
        }
        projectListJson +=']';
        //System.debug('项目列表:'+projectListJson);
    }
    ///获取选中项目的详细信息
    public void getProjectsInfo(){
        if(String.isBlank(dpId) == false){
            isEdit = (fatherId == 'edit') ? true :false;
            for(DevelopProject__c dpt :dpList){
                if((dpt.Id+'') == dpId){
                    dp = dpt; 
                    break;
                }
            }
        }else{
            isEdit = true;
            dp = new DevelopProject__c();
            dp.OwnerId = uid;


        }

    }
    ///增加或者更新项目
    public void addProject(){
        try{
            upsert dp;
            isEdit = false;
            isSuccess = true;
        }catch(Exception e){
            isSuccess = false;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
    }
    //删除项目
    public void removeProject(){
        Savepoint sp = Database.setSavepoint();
        if(dp.Id !=null){
            if(dp.OwnerId != uid){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '不是项目的所有人不能删除项目!'));
                return;
            }
            if(dp.Status__c !='未开始' || dp.Status__c != null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '项目已经开始不能删除项目!'));
                return;
            }
            try{
                pid = dp.Id;
                getProjectStruct();
                if(pmdList.size() > 0) delete pmdList;
                delete dp;
                isSuccess = true;
            }catch(Exception e){
                Database.rollback(sp);
                isSuccess = false;
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));

            }

        } 
    }
    //=================================项目子任务列表==================================== 

    //获取项目的结构 并生成树状的json
    public void getProjectStruct(){
        ///查询 任务明细
        pmdList =[select Id, name ,Owner__c,StartTime__c,
                  TaskDescrible__c,Status__c,FatherTaskDetail__c,
                  EndTime__c,estimateTime__c,EstimateDate__c,Remark__c
                  from ProjectManageDetail__c where Project__c =:pid];

        projectJson = String.valueOf(calculateStuct(pmdList,null).get('Struct'));
        //System.debug('项目层级结构:'+projectJson);

    }
    ///更新子任务的最新的预计完成时间
    public void refreshEstimate(){
    	
        update pmdList;
    }
    
    
    //获取选中的任务的详细信息
    public void getProjectDetail(){

        if(String.isBlank(pdId) == true){
            isEdit = true;

            pmd = new ProjectManageDetail__c();
            if(String.isBlank(fatherId) == false) pmd.FatherTaskDetail__c = fatherId;
            pmd.Project__c = pid;
            pmd.Owner__c = uid;
            pmd.StartTime__c = Date.today();
            pmd.estimateTime__c = 1;
            pmd.Status__c ='未开始';
        }else{

            isEdit = (fatherId == 'edit') ? true :false;
            for(ProjectManageDetail__c p :pmdList){
                if(pdId == (p.Id+'') ){
                    pmd = p;
                    break;
                }
            }
        }

    }

    //增加新的节点 子任务
    public void addNode(){
        try{
            upsert pmd;
            isEdit = false;
            isSuccess = true;
        }catch(Exception e){
            isSuccess = false;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }

    }

    ///删除节点 子任务  
    public void removeNode(){

        if(String.isBlank(pdId) == false){
            ///获取要删除的节点 和 子节点
            List<ProjectManageDetail__c> deleteList = getChilds(null,pdId);

            try{
                if(deleteList.size()>0)delete deleteList;
                isSuccess = true;
            }catch(Exception e){
                isSuccess = false;
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            }
        }
    }
    ///迭代 找出传入节点及所有字节点
    public List<ProjectManageDetail__c> getChilds(Set<String> fatherIds, Id fatherId){
        List<ProjectManageDetail__c> temp = new List<ProjectManageDetail__c>();
        Set<String> fIds = new Set<String>();
        for(ProjectManageDetail__c p:pmdList){
            if(fatherIds == null){//如果传入的是Id
                if(p.Id == fatherId){//将这条数据加入列表
                    temp.add(p);
                }else if(p.FatherTaskDetail__c == fatherId){//统计子任务
                    fIds.add(p.Id);
                }
            }
            if(fatherId == null){//传入的是子任务的ID列表
                if(fatherIds.contains(p.Id)){
                    temp.add(p);///加入列表
                }
                if(fatherIds.contains(p.FatherTaskDetail__c)){//统计子任务
                    fIds.add(p.Id);
                }
            }

        }
        if(fIds.size()>0)temp.addAll(getChilds(fIds,null));

        return temp;

    }
    ///迭代 计算项目的结构
    public  Map<String,Object> calculateStuct(List<ProjectManageDetail__c> pmdList,Id fatherId){
        List<ProjectManageDetail__c> te = new List<ProjectManageDetail__c>();

        Map<String,Object> structs = new Map<String,Object>();

        //找出当层的所有任务
        for(ProjectManageDetail__c p:pmdList){
            if(p.FatherTaskDetail__c == fatherId){
                te.add(p);
            }
        }



        String nodeList = '';
        nodeList += '[';
        integer i = 0;
        Date maxdate = null;///本层最大完成时间;
        for(ProjectManageDetail__c p : te){
            i ++;
          
            Map<String,Object> rs = calculateStuct(pmdList,p.Id);
            String children =(String) rs.get('Struct');
            ///更新最大的完成时间
           Date estimateDate = (Date) rs.get('EndDate');
            if(estimateDate != null)p.EstimateDate__c = estimateDate;

            ////生成项目的结构

            String isParent = children.length() > 2 ? 'true':'false';
            if(p.FatherTaskDetail__c == null) isParent = 'true';
            String fId = p.FatherTaskDetail__c == null ? '':p.FatherTaskDetail__c;
             String node = '';
            node +='{';
            node += 'name:"'+p.Name+'",';
            node += 'Id:"'+p.Id +'",';
            node += 'children:'+children+',';
            node += 'fId:"'+fId+'",';
            node += 'isParent:'+isParent+'}';
            nodeList += node ; 
            if(i != te.size())nodeList +=',';

            ///计算本层 最大的完成时间
            Date currentDate =p.Status__c == '完成' ? p.EndTime__c :p.EstimateDate__c;

            maxdate =  maxdate == null ? currentDate : (maxdate > currentDate ? maxdate : currentDate);

            System.debug('****'+p.Name +':' +maxdate +':'+currentDate);

        }
        nodeList +=']';
        structs.put('Struct',nodeList);
        structs.put('EndDate',maxdate);

        return structs;
    }

    ///
    public class ProjectStructBean{
        public String name; //节点名字
        public String Id;//节点id 
        public List<ProjectStructBean> children;//子节点
        public Date estimateEndDate;// 预计完成时间
    }
    */
}